package cn.com.gridinfo.sooc.core.course;


import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocFragment;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.course.classes.activity.CourseDetailActivity;
import cn.com.gridinfo.sooc.core.course.classes.adapter.CourseListAdapter;
import cn.com.gridinfo.sooc.core.course.classes.adapter.XnCarouseImageView;
import cn.com.gridinfo.sooc.core.course.classes.bean.CarourseFigure;
import cn.com.gridinfo.sooc.core.course.common.CodeConst;
import cn.com.gridinfo.sooc.core.course.classes.dao.CourseDao;
import cn.com.gridinfo.sooc.utils.IntentUtil;
import cn.com.gridinfo.sooc.utils.MessageUtils;

/**
 * 校内主页
 */
public class XnMainFragment extends BaseSoocFragment {

    View view;
    @InjectView(R.id.xn_lunbo_layout)
    AppBarLayout xnLunboLayout;//轮播图播放区域
    @InjectView(R.id.xn_lunbo_view)
    XnCarouseImageView xnLunboView;//轮播图

    @InjectView(R.id.course_main_list)
    UltimateRecyclerView course_main_recylerView;//课程列表控件

    CourseListAdapter courseListAdapter;//课程列表适配器

    CourseDao dao;//课程分类 dao
    LinearLayoutManager linearLayoutManager;//列表管理器

    List<CarourseFigure> cfList = new ArrayList<>();//轮播图列表数据

    //分页数据
    int pageNo = 1;
    int pageSize = 10;
    int maxLastPositon;//数据最后位置



    public static XnMainFragment newInstance() {
        return new XnMainFragment();
    }

    public XnMainFragment() {
    }

    //当页面可见时
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        //判断Fragment中的ListView时候存在，判断该Fragment时候已经正在前台显示  通过这两个判断，就可以知道什么时候去加载数据了
        if (isVisibleToUser && isVisible() ) {
            //未登录时会实例化校内页面,未登录无需调用接口
            if(!StringUtils.isNull(Arad.preferences.getString(LocalMark.OUATH_TOKEN.getName(),""))) {
                dao.getCourseListByPage("", "", pageNo, CodeConst.COURSE_LIST_FIRST);
                //获取轮播图数据
                dao.getCourseLunBo(); //加载数据的方法
            }
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.course_xn_main_fragment, null);
        ButterKnife.inject(this, view);
        dao = new CourseDao(this);
        //未登录时会实例化校内页面,未登录无需调用接口
        if(!StringUtils.isNull(Arad.preferences.getString(LocalMark.OUATH_TOKEN.getName(),""))) {
            dao.getCourseListByPage("", "", pageNo, CodeConst.COURSE_LIST_FIRST);
            //获取轮播图数据
            dao.getCourseLunBo(); //加载数据的方法
        }
        //初始化listView
        linearLayoutManager = new LinearLayoutManager(getActivity());
        course_main_recylerView.setLayoutManager(linearLayoutManager);


        return view;
    }



    /**
     * 请求成功
     */
    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao.status.equals("0")) {
                switch (requestCode) {
                    //课程首次请求
                    case CodeConst.COURSE_LIST_FIRST:
                        initCourseList();
                        break;

                    //课程刷新操作
                    case CodeConst.COURSE_LIST_PUSHDOWN:
                        //刷新结束
                        course_main_recylerView.setRefreshing(false);

                        if (dao.getCourseList() != null && !dao.getCourseList().isEmpty()) {
                            course_main_recylerView.hideEmptyView();
                        } else {
                            //无数据处理
                            course_main_recylerView.showEmptyView();
                        }
                        //刷新数据
                        courseListAdapter.refresh(dao.getCourseList());


                        if (dao.getCourseList().size() > (pageSize - 1))
                            //数据大于每页显示的条数,则加载更多数据 view 显示
                            courseListAdapter.loadMoreDataView();
                        else {
                            //数据小于当前页的话则不显示加载更多,显示没有更多了
                            courseListAdapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;

                    //课程翻页操作
                    case CodeConst.COURSE_LIST_PULLUP:
                        if (dao.getCourseList() != null && !dao.getCourseList().isEmpty()) {
                            //加载更多
                            courseListAdapter.loadmore(dao.getCourseList());
                        } else {
                            //数据加载完成,没有更多数据,显示没有更多了
                            courseListAdapter.loadNoDataView();
                            //无数据则不显示下一页
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;

                    //设置轮播图
                    case CodeConst.COURSE_CAROURSEFIGURE:
                        cfList = dao.getLunBoList();
                        // 设置轮播图
                        initLunBoImage();
                        break;

                }
            } else {
                MessageUtils.showImageShortToast(getActivity(), dao.statusCode);
            }

        } catch (Exception e) {
            Log.d(e.getMessage(), e);
            // MessageUtils.showImageShortToast(getActivity(),"请求数据异常");
        }
    }


    /**
     * 初始化 课程 list 数据 分页
     */
    private void initCourseList() {

        courseListAdapter = new CourseListAdapter(dao.getCourseList(), getActivity(), true);
        course_main_recylerView.setAdapter(courseListAdapter);


        course_main_recylerView.enableLoadmore();
        course_main_recylerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                        //下拉刷新 账户明细数据
                        pageNo = 1;//首页
                        dao.getCourseListByPage("", "", pageNo, CodeConst.COURSE_LIST_PUSHDOWN);
                        linearLayoutManager.scrollToPosition(0);
                    }

        });
        course_main_recylerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {

                        if (itemsCount > (pageSize - 1)) {
                            maxLastPositon = maxLastVisiblePosition;
                            dao.getCourseListByPage("", "", ++pageNo, CodeConst.COURSE_LIST_PULLUP);
                        } else {
                            //加载数据完成,没有更多数据,显示没有更多了
                            courseListAdapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
                        }
                    }

        });


        courseListAdapter.setmOnItemClickLitener(new CourseListAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                Log.d("点击第"+position+"个");
                String kcid = courseListAdapter.courseList.get(position).getKcid();
                String kcfm = courseListAdapter.courseList.get(position).getKcfm();
                Log.d("课程ID:"+kcid);
                IntentUtil.intentSlidIn(getActivity(),CourseDetailActivity.class,00,new BasicNameValuePair("kcid",kcid),new BasicNameValuePair("kcfm",kcfm));
            }
        });
    }

    /**
     * 初始化文轮播图
     */
    private void initLunBoImage() {
        if (null == cfList || cfList.isEmpty()) {
            xnLunboLayout.setVisibility(View.GONE);
        } else {
            xnLunboLayout.setVisibility(View.VISIBLE);

            xnLunboView.setImagesUrl(cfList);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
